package com.yc.javaee.servlet.d0618;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    // 常量命名规则 大写 + _
    public static final Map<String,Long> USER_MAP = new HashMap<>();

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is added to a session. */
        sbe.getName();// 获取添加的属性名
        sbe.getValue();// 添加的属性值
        HttpSession session = sbe.getSession();//  获取会话对象
        System.out.println(USER_MAP);
        if("loginedUser".equals(sbe.getName())){
            // 表示有用户登录, 将用户记录到map中
            USER_MAP.put((String)sbe.getValue(), new Date().getTime());
        }
        System.out.println(USER_MAP);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        if("loginedUser".equals(sbe.getName())){
            // 表示有用户登录, 将用户记录到map中
            USER_MAP.remove((String)sbe.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
    }
}
